package org.yong.springbootcmd.service.impl;

import com.google.common.collect.Maps;

import java.util.Map;

import org.springframework.stereotype.Service;
import org.yong.springbootcmd.model.vo.WsProtocol;
import org.yong.springbootcmd.service.WsProtocolHandler;

@Service("WsProtocolHandlerBase")
public class WsProtocolHandlerBaseImpl implements WsProtocolHandler {

    // 处理器仓库
    private static Map<Integer, WsProtocolHandlerBaseImpl> handlers = Maps.newHashMap();

    // 协议参数
    protected WsProtocol param;

    // 自动注册
    {
        int mainCmd = this.getMainCmd();
        if (0 > mainCmd) {
            String msg = String.format("注册到处理器失败, 主命令无效: %d", mainCmd);
            throw new ExceptionInInitializerError(msg);
        }

        if (handlers.containsKey(mainCmd) && !this.isForceRegister()) {
            String s = String.format("已存在相同业务处理器, mainCmd:%d", mainCmd);
            throw new ExceptionInInitializerError(s);
        }

        handlers.put(mainCmd, this);
    }

    @Override
    public final WsProtocol handle(WsProtocol wp) {
        int mainCmd = wp.getM();
        if (!handlers.containsKey(mainCmd)) {
            return WsProtocol.notFound(wp);
        } else {
            WsProtocolHandlerBaseImpl wph = handlers.get(mainCmd);
            wph.param = wp;
            return wph.doHandle();
        }
    }

    @Override
    public int getMainCmd() {
        return 0;
    }

    @Override
    public boolean isForceRegister() {
        return false;
    }

    /**
     * 执行处理
     *
     * @return 处理结果
     */
    protected WsProtocol doHandle() {
        return WsProtocol.notFound(param);
    }
}
